package com.framework;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;

/**
 *  * 企业级业务组件化框架
 *  * 完整功能：组件化处理、配置化工作流、缓存、多线程、日志、定时任务、数据校验、加解密、权限、文件处理、事务
 */
public class EnterpriseComponentFramework {

    public static void main(String[] args) {
        try {
            demoFramework();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void demoFramework() throws Exception {
        System.out.println("===== 企业级业务组件框架演示 =====");
        
        // 1. 初始化框架核心
        ComponentRegistry registry = new ComponentRegistry();
        WorkflowEngine engine = new WorkflowEngine(registry);
        ConfigManager configManager = new ConfigManager();
        
        // 2. 加载业务配置
        BusinessWorkflow userRegistrationFlow = configManager.loadWorkflow("user-registration");
        
        // 3. 注册核心组件
        registry.registerComponent(new ValidationComponent());
        registry.registerComponent(new UserServiceComponent());
        //registry.registerComponent(new FileServiceComponent());

        // 4. 创建增强组件（带缓存、日志和异步）
        Component userService = ComponentBuilder.forComponent(registry.getComponent("UserService"))
            .withLogging()
            .withCaching(300)
            .withAsync(ForkJoinPool.commonPool())
            .build();
        registry.registerComponent(userService, "EnhancedUserService");
        
        // 5. 准备请求数据
        UserRegistrationRequest request = new UserRegistrationRequest();
        request.setUsername("john_doe");
        request.setPassword("Secure@123");
        request.setEmail("john@example.com");
        request.setBirthDate("1990-05-15");
        //request.setProfileImage(new FileInput("profile.jpg", Files.readAllBytes(Path.of("sample.jpg"))));
        
        ComponentContext context = new ComponentContext<>();
        context.setRequestData(request);
        context.getContextData().put("clientIp", "192.168.1.100");
        context.getContextData().put("currentUser", "admin");
        
        // 6. 执行工作流
        ComponentOutput<UserRegistrationResponse> output = (ComponentOutput<UserRegistrationResponse>)engine.execute(userRegistrationFlow, context);
        
        // 7. 处理结果
        if (output.isSuccess()) {
            UserRegistrationResponse response = output.getData();
            System.out.println("✅ 用户注册成功! 用户ID: " + response.getUserId());
        } else {
            System.out.println("❌ 注册失败: " + output.getErrorMessage());
        }
        
        // 8. 测试定时任务
        Scheduler scheduler = new Scheduler();
        scheduler.schedule("dailyReport", new DailyReportComponent(), 
                          0, 24, TimeUnit.HOURS);
        
        System.out.println("===== 演示完成 =====");
    }
}
